package withouther.system.plugins.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import withouther.system.core.aop.log.Log;
import withouther.system.core.base.BaseController;
import withouther.system.core.result.WhResult;
import withouther.system.plugins.system.entity.Role;
import withouther.system.plugins.system.entity.User;
import withouther.system.plugins.system.service.UserService;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
* @Author tzq
* @Description //TODO
* @Date 14:48 2020/3/19
**/
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController extends BaseController {

    @Resource
    private UserService userService;

    @Log("查询用户")
    @ApiOperation("分页")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:user:view')")
    public WhResult page(@RequestParam Map<String, Object> params) {
        try {
//            System.out.println(roleService.queryPage(params));
            return WhResult.success(userService.queryPage(params));
        } catch (Exception e) {
            log.error("page error", e);
            return WhResult.fail("系统繁忙，请稍后再试");
        }
    }

    @Log("添加用户")
    @ApiOperation("添加")
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('system:user:add')")
    public WhResult add(@Valid @RequestBody User user) {
        try {
            return WhResult.success(userService.addUser(user));
        } catch (Exception e) {
            log.error("add error", e);
            return WhResult.fail("系统繁忙，请稍后再试");
        }
    }

    @Log("修改用户")
    @ApiOperation("修改")
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('system:user:upd')")
    public WhResult update(@Valid @RequestBody User user) {
        try {
            return WhResult.success(userService.updateUser(user));
        } catch (Exception e) {
            log.error("add error", e);
            return WhResult.fail("系统繁忙，请稍后再试");
        }
    }

    @Log("删除用户")
    @ApiOperation("删除" )
    @DeleteMapping("/delete" )
    @PreAuthorize("hasAuthority('system:user:del')")
    public WhResult delete(@RequestBody List<Long> ids) {
        try {
            return  WhResult.success(userService.deleteUserByIdAndRole(ids));
        } catch (Exception e) {
            log.error("delete error",e);
            return WhResult.fail("系统繁忙，请稍后再试");
        }
    }
}
